package com.example.partner.activity.team;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.content.Intent;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.example.partner.R;
import com.example.partner.common.BaseResponse;
import com.example.partner.model.request.TeamAddRequest;
import com.example.partner.service.TeamService;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class BuildTeamActivity extends AppCompatActivity {

    final String TAG = "BuildTeamActivity";
    private EditText edname,edpwd,eddescripe,edannounce,edplace,edmaxnum,edlable,eddate;
    private Button btn;
    private RadioGroup radioGroup;
    private TeamService teamService;
    private Integer status;
    private LinearLayout layout;
    ImageView teamimg;
    private static final int PICK_IMAGE_REQUEST = 1;
    private static final int TAKE_PHOTO_REQUEST = 2;
    Uri photoUri;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_build_team);
        // 初始化UI组件
        edname=findViewById(R.id.edteamname);
        edpwd=findViewById(R.id.edpwd);
        eddescripe=findViewById(R.id.edDescripe);
        edannounce=findViewById(R.id.edannounce);
        edplace=findViewById(R.id.edplace);
        edmaxnum=findViewById(R.id.edmaxnum);
        eddate=findViewById(R.id.eddate);
        edlable=findViewById(R.id.edlable);
        btn=findViewById(R.id.btnBuild);
        radioGroup=findViewById(R.id.regroup);
        teamimg=findViewById(R.id.teamimg);
        layout=findViewById(R.id.la);
//        获取单选内容
        radioGroup.setOnCheckedChangeListener((radioGroup, i) -> {
            RadioButton radioButton=findViewById(i);
            String radiotext=radioButton.getText().toString();
            if(radiotext.equals("公开")){
                status=0;
                layout.setVisibility(View.GONE);
            };
            if(radiotext.equals("私有")){
                status=1;
                layout.setVisibility(View.GONE);
            };
            if(radiotext.equals("加密")){
                status=2;
                layout.setVisibility(View.VISIBLE);
            };
        });
        // 初始化Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        teamService = retrofit.create(TeamService.class);
        btn.setOnClickListener(view ->buildTeam());
        // 设置头像点击事件
        teamimg.setOnClickListener(v -> {
            // 选择头像逻辑
            selectAvatar();
        });
    }

    private void selectAvatar() {
        // 处理选择或拍摄头像的逻辑
        final CharSequence[] items = {"从相册选择", "拍照", "取消"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("更换头像");
        builder.setItems(items, (dialog, item) -> {
            if (items[item].equals("从相册选择")) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(intent, PICK_IMAGE_REQUEST);
            } else if (items[item].equals("拍照")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                    } catch (IOException ex) {
                        // 错误处理
                    }
                    if (photoFile != null) {
                        photoUri = FileProvider.getUriForFile(this, "com.example.partner.fileprovider", photoFile);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                        startActivityForResult(intent, TAKE_PHOTO_REQUEST);
                    }
                }
            } else if (items[item].equals("取消")) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    private File createImageFile() throws IOException {
        // 创建一个文件名
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* 前缀 */
                ".jpg",         /* 后缀 */
                storageDir      /* 目录 */
        );

        return image;
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == TAKE_PHOTO_REQUEST) {
                // 显示拍摄的图片
                teamimg.setImageURI(photoUri);

            }
            if (requestCode == PICK_IMAGE_REQUEST) {
                photoUri = data.getData();
                teamimg.setImageURI(photoUri);

            }

        }
    }

    private File saveImageToStorage(Bitmap bitmap) {
        FileOutputStream outStream = null;
        File file=null;
        try {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            file = new File(getExternalFilesDir(null), "saved_image.jpg"+timeStamp); // 文件保存路径和名称
            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (outStream != null ) outStream.close(); } catch (Exception ex) { ex.printStackTrace(); }
        }
        return file;
    }

    private String getImagePathFromStorage(File file) {
        return file.getAbsolutePath();
    }

    private void buildTeam() {
        String imagePath=null;
        if(photoUri!=null){
            try {
                // 从URI获取Bitmap
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
                // 保存Bitmap到文件
                File file=saveImageToStorage(bitmap);
                // 获取文件路径或URI，并存储到数据库中
                imagePath = getImagePathFromStorage(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String name =edname.getText().toString();
        String pwd = edpwd.getText().toString();
        String descripe = eddescripe.getText().toString();
        String announce =edannounce.getText().toString();
        String place = edplace.getText().toString();
        String []lable =edlable.getText().toString().split(",");
        List<String> list = Arrays.asList(lable);
        Integer maxnum=4;//默认为4
        if(!edmaxnum.getText().toString().isEmpty()) {
            maxnum = Integer.parseInt(edmaxnum.getText().toString());
        }
        String date=eddate.getText().toString();
        if(date.isEmpty()){
            date="2222-12-31";//默认过期时间为2222-12-31
        }
        SharedPreferences sharedPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        Long userid=sharedPreferences.getLong("userId",-1);

       TeamAddRequest request = new TeamAddRequest();
        request.setName(name);
        request.setPassword(pwd);
        request.setDescription(descripe);
        request.setAnnounce(announce);
        request.setPlace(place);
        request.setMaxNum(maxnum);
        request.setUserId(userid);
        request.setExpireTime(date);
        request.setDescription(descripe);
        request.setTags(list.toString());
        request.setStatus(status);
        request.setAvatarUrl(imagePath);


        teamService.addTeam(request).enqueue(new Callback<BaseResponse<Long>>() {
            @Override
            public void onResponse(Call<BaseResponse<Long>> call, Response<BaseResponse<Long>> response) {
                if (response.isSuccessful()&&response.body().getData()!=null) {
                    // 处理成功的响应
                    Toast.makeText(BuildTeamActivity.this,"创建队伍成功！",Toast.LENGTH_SHORT).show();
                    BuildTeamActivity.this.finish();
                } else {
                    Toast.makeText(BuildTeamActivity.this,"过期时间格式不正确",Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<BaseResponse<Long>> call, Throwable t) {
                Toast.makeText(BuildTeamActivity.this, "请检查队伍名称和过期时间", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
